package com.example.teaculture.service;


import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;


import com.example.teaculture.DB.DBOpenHelper;
import com.example.teaculture.tools.User;


public class UserService {
  private DBOpenHelper dbHelper;
  public UserService(Context context){
    dbHelper=new DBOpenHelper(context);
  }


  public UserService() {

  }
  public User getUser(String email,User user){
    Cursor c ;
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    String sql="select * from user where username=?";
    int age = 0;
    String sex = null;
    try{
      c=db.rawQuery(sql,new String[]{email});
      while (c.moveToNext()){
        sex = c.getString(c.getColumnIndex("sex"));
        age = c.getInt(c.getColumnIndex("age"));
      }
      db.close();
      user.setUsername(email);
      user.setAge(age);
      user.setSex(sex);
      return  user;

    }
    catch (NullPointerException exception){
      return null;
    }
  }

  public void update(User user){
    SQLiteDatabase sdb=dbHelper.getReadableDatabase();
    try {
        String sql = "update user set sex=?,age=? where username=?";
        Object obj[] = {user.getSex(), user.getAge(), user.getUsername()};
        sdb.execSQL(sql, obj);
    }catch (Exception e){
        System.out.println("也不知出了啥问题");
    }

 }

  public boolean login(String username,String password){
    SQLiteDatabase sdb=dbHelper.getReadableDatabase();
    String sql="select * from user where username=? and password=?";
    Cursor cursor=sdb.rawQuery(sql, new String[]{username,password});
    if(cursor.moveToFirst()==true){
      cursor.close();
      return true;
    }
    return false;
  }
  public boolean register(User user){
      SQLiteDatabase sdb = dbHelper.getReadableDatabase();
      String sql = "insert into user(username,password,age,sex) values(?,?,?,?)";
      Object obj[] = {user.getUsername(), user.getPassword(), user.getAge(), user.getSex()};
      sdb.execSQL(sql, obj);
      return true;
  }
  public boolean isEmail(String strEmail){
    String string="^([a-zA-Z0-9_-]+)@(163.com|qq.com|42du.cn)+$";
    if(TextUtils.isEmpty(string)){
      return false;
    }
    else{
      return strEmail.matches(string);
    }
  }
}
